package drds.plus.executor.command_handler.query.join;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.command_handler.query.AbstractQueryHandler;
import drds.plus.executor.cursor.cursor.ISortingCursor;
import drds.plus.executor.data_node_executor.DataNodeExecutorContext;
import drds.plus.executor.repository.Repository;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.ExecutePlan;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.query.Join;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.query.Query;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

@Slf4j
public class IndexBlockNestedtLoopJoinHandler extends AbstractQueryHandler {

    public IndexBlockNestedtLoopJoinHandler() {
        super();
    }

    protected ISortingCursor doQuery(ExecuteContext executeContext, ExecutePlan executePlan, ISortingCursor cursor) throws RuntimeException {

        Join join = (Join) executePlan;
        Repository repository = executeContext.getRepository();
        Query leftNode = join.getLeftNode();

        ISortingCursor cursorLeft = DataNodeExecutorContext.getExecutorContext().getDataNodeExecutor().execute(executeContext, leftNode);

        if (!join.getRightNode().isSubQuery()) {
            /**
             * 右边调的是mget，所以不需要在创建的时候初始化
             */
            join.getRightNode().setLazyLoad(true);
        }
        ISortingCursor cursorRight = DataNodeExecutorContext.getExecutorContext().getDataNodeExecutor().execute(executeContext, join.getRightNode());

        if (join.getRightNode().isSubQuery()) {
            cursorRight = repository.getCursorFactory().temporaryTableCursor(executeContext, cursorRight, null, true, join.getRightNode().getRequestId());
        }
        cursor = repository.getCursorFactory().indexBlockNestedLoopCursor(executeContext, join, cursorLeft, join.getLeftJoinColumnList(), cursorRight, join.getRightJoinColumnList(), join.getItemList());
        return cursor;
    }

    public Logger log() {
        return log;
    }
}
